<template>
  <div>
    <el-descriptions border :column="2">
      <el-descriptions-item label="受检人姓名" align="center">
        <div
          class="w-full flex justify-between items-center"
          v-if="flowActiveIndex == 1"
        >
          <el-input
            v-model="checkDetailForm.relationName"
            placeholder="请点击选择受检人"
            readonly
            @click="handleClickChangeCustomer"
            :style="{
              width: flowActiveIndex == 1 ? '82%' : '100%',
            }"
            class="h-[1.4rem]"
            v-if="flowActiveIndex == 1"
          />

          <el-icon
            size="20"
            v-if="flowActiveIndex == 1"
            class="hover:cursor-pointer"
            title="新增受检人"
            @click="handleClickInsertCustomer"
          >
            <Plus />
          </el-icon>
        </div>
        <div
          class="max-w-[80%] ellipsis-single"
          v-if="flowActiveIndex == 2"
          :title="checkDetailForm.relationName"
        >
          {{ checkDetailForm.relationName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item
        label="检查单号"
        align="center"
        v-if="flowActiveIndex == 2"
      >
        <div class="w-full flex justify-between items-center">
          <el-input
            v-model="checkDetailForm.code"
            placeholder="请点击选择受检人"
            readonly
            @click="handleClickChangeCheck"
            :style="{
              width: flowActiveIndex == 2 ? '82%' : '100%',
            }"
          />

          <el-icon
            size="20"
            v-if="flowActiveIndex == 2"
            class="hover:cursor-pointer"
            title="新增检查单号"
            @click="handleClickInsertCheck"
          >
            <Plus />
          </el-icon>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="受检人联系方式" align="center">
        <el-input
          v-model="checkDetailForm.phone"
          placeholder="请选择选择受检人"
          v-if="checkDetailForm.relationId && flowActiveIndex == 1"
        />
        <div v-else>
          {{ checkDetailForm.phone || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="受检人性别" align="center">
        {{
          checkDetailForm.sex == 1 ? "男" : checkDetailForm.sex == 2 ? "女" : ""
        }}
      </el-descriptions-item>
      <el-descriptions-item label="受检人年龄" align="center">
        {{ checkDetailForm.age || "" }}
      </el-descriptions-item>
      <el-descriptions-item
        label="测量时间"
        align="center"
        v-if="flowActiveIndex == 2"
      >
        <div class="w-full" truncated>
          {{ checkDetailForm.createdAt || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item
        label="工作环境"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        <div class="w-full">
          <el-select
            v-model="checkDetailForm.workEnvironment"
            placeholder="请选择工作环境"
            filterable
            @change="handleBlurEdit"
          >
            <el-option
              v-for="item in workEnvList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </div>
      </el-descriptions-item>
      <el-descriptions-item
        label="职业"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        <div class="w-full">
          <el-select
            v-model="checkDetailForm.occupation"
            placeholder="请选择职业"
            filterable
            @change="handleBlurEdit"
          >
            <el-option
              v-for="item in occupationList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </div>
      </el-descriptions-item>
      <el-descriptions-item
        label="用眼距离"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        <div class="w-full">
          <el-select
            v-model="checkDetailForm.eyeDistance"
            placeholder="请选择用眼距离"
            filterable
            @change="handleBlurEdit"
          >
            <el-option
              v-for="item in eyeDistanceList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </div>
      </el-descriptions-item>

      <el-descriptions-item
        label="客户姓名"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        {{ checkDetailForm.customerName || "" }}
      </el-descriptions-item>
      <el-descriptions-item
        label="客户联系方式"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        {{ checkDetailForm.customerTel || "" }}
      </el-descriptions-item>
      <el-descriptions-item
        label="关系"
        align="center"
        v-if="flowActiveIndex == 1"
      >
        <el-tag v-if="checkDetailForm && checkDetailForm.baseRelationName">
          {{ checkDetailForm.baseRelationName || "" }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item
        label="主诉"
        align="center"
        v-if="flowActiveIndex == 2"
      >
        <el-input
          v-model="checkDetailForm.complaints"
          placeholder="请输入主诉"
          type="textarea"
          :rows="1"
          :disabled="!checkDetailForm.code"
          :title="!checkDetailForm.code ? '请先选择检查单号' : ''"
        />
      </el-descriptions-item>
    </el-descriptions>

    <el-drawer
      v-model="change_customer_drawer"
      title="选择受检人"
      size="80%"
      destroy-on-close
    >
      <ChangeCustomer :type="2" @handleBack="handleSuccessChangeCustomer" />
    </el-drawer>

    <el-drawer
      v-model="change_check_drawer"
      title="选择检查单号"
      size="80%"
      destroy-on-close
    >
      <ChangeCheck
        :relationId="checkDetailForm.relationId"
        @handleBack="handleSuccessChangeCheck"
      />
    </el-drawer>

    <el-drawer
      v-model="insert_customer_drawer"
      title="新增客户/受检人"
      size="40%"
      destroy-on-close
    >
      <InsertCustomer
        ref="insertCustomerRef"
        :workEnvList="workEnvList"
        :occupationList="occupationList"
        :eyeDistanceList="eyeDistanceList"
        @handleSuccessBack="handleSuccessInsertCustomer"
        @handleBack="handleErrorInsertCustomer"
      />
      <template #footer>
        <el-button @click="insert_customer_drawer = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleAffirmCustomer"
          :loading="customer_loading"
        >
          {{ customer_loading ? "提 交 中" : "提 交" }}
        </el-button>
      </template>
    </el-drawer>

    <InsertCheck
      ref="insert_check_ref"
      :flag="true"
      @handleBack="handleSuccessInsert"
      v-show="false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { cloneDeep } from "lodash";
import ChangeCustomer from "@/components/ChangeCustomer.vue";
import ChangeCheck from "@/components/ChangeCheck.vue";
import InsertCustomer from "@/view/ManageMode/CustomerList/component/InsertUpdate.vue";
import InsertCheck from "@/view/ManageMode/CheckList/component/InsertUpdate.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  ListCustomerOccupation,
  ListCustomerEyeUsageDistance,
  ListCustomerWorkEnv,
} from "../../../wailsjs/go/api/CustomerApi.js";
import { ListProjectInfos } from "../../../wailsjs/go/api/ReportApi";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";

onMounted(() => {
  // getOccupationList();
  // getWorkEnvList();
  // getEyeUsageDistanceList();
});

const userStore = useUserStore();
const { cutStatus, flowActiveIndex, checkDetailForm } = storeToRefs(userStore);

// 1.选择受检人
const change_customer_drawer = ref(false);
// 选择受检人按钮
const handleClickChangeCustomer = () => {
  change_customer_drawer.value = true;
};
const handleSuccessChangeCustomer = (data) => {
  let {
    id,
    name,
    phone,
    sex,
    age,
    ageValid,
    birthday,
    customerId,
    customerName,
    baseRelationId,
    baseRelationName,
    email,
    headUrl,
    workEnvName,
    occupationName,
    eyeUsageDistanceName,
    organId,
    medicalCardNumber,
    address,
  } = cloneDeep(data);
  let item = {
    relationId: id, // 受检人id
    relationName: name, // 受检人姓名
    phone: phone, // 受检人联系方式
    sex: sex, // 受检人性别
    age: age, // 受检人年龄
    ageValid: ageValid, // 受检人年龄是否有效
    birthday: birthday, // 受检人生日
    customerId: customerId, // 客户id
    customerName: customerName, // 客户姓名
    baseRelationId: baseRelationId, // 客户关系id
    baseRelationName: baseRelationName, // 客户关系
    headUrl: headUrl, // 客户头像
    workEnvironment: workEnvName, // 工作环境
    occupation: occupationName, // 职业
    eyeDistance: eyeUsageDistanceName, // 用眼距离
    organId: organId,
    medicalCardNumber: medicalCardNumber,
  };
  // console.log(item);
  checkDetailForm.value = item;
  change_customer_drawer.value = false;
  userStore.updateFlowActiveIndex(2);
};

// 2.选择检查单号
const change_check_drawer = ref(false);
// 选择检查单号按钮
const handleClickChangeCheck = () => {
  change_check_drawer.value = true;
};
// 选择完检查单号
const handleSuccessChangeCheck = (data) => {
  // console.log(data);
  checkDetailForm.value.id = data.id || null;
  checkDetailForm.value.code = data.code || "";
  checkDetailForm.value.customerTel = data.customerPhone || "";
  checkDetailForm.value.projectList = data.projectList || [];
  checkDetailForm.value.projectList.forEach((item) => {
    item.isChecked = true;
  });
  checkDetailForm.value.origin = data.origin || "";
  checkDetailForm.value.organId = data.organId || null;
  checkDetailForm.value.companyName = data.companyName || "";
  checkDetailForm.value.createdAt = data.createdAt || "";

  checkDetailForm.value.customerId = data.customerId || null;
  checkDetailForm.value.customerName = data.customerName || "";
  checkDetailForm.value.baseRelationName = data.baseRelationName || "";

  checkDetailForm.value.complaints = data.complaints || "";

  setStorageWithEvent("refresh_region_item");
  change_check_drawer.value = false;
};

const insert_check_ref = ref(null);
const handleClickInsertCheck = () => {
  ElMessageBox.confirm("您确定要新增检查单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    insert_check_ref.value?.handleSubmit({
      baseRelationId: checkDetailForm.value.baseRelationId,
      relationId: checkDetailForm.value.relationId,
      relationName: checkDetailForm.value.relationName,
      sex: checkDetailForm.value.sex,
      age: checkDetailForm.value.age,
      phone: checkDetailForm.value.phone,
      customerId: checkDetailForm.value.customerId,
      customerName: checkDetailForm.value.customerName,
      customerPhone: checkDetailForm.value.customerPhone,
      sex: checkDetailForm.value.sex,
      workEnvironment: checkDetailForm.value.workEnvironment,
      occupation: checkDetailForm.value.occupation,
      eyeDistance: checkDetailForm.value.eyeDistance,
      projectList: checkDetailForm.value.projectList,
    });
  });
};
// 一键创建检查单成功
const handleSuccessInsert = (data) => {
  console.log(data);

  checkDetailForm.value.id = data.id || null;
  checkDetailForm.value.code = data.code || "";
  checkDetailForm.value.projectIds = data.projectIds || [];
  checkDetailForm.value.projectList = [];
  checkDetailForm.value.projectIds.forEach((item) => {
    checkDetailForm.value.projectList.push({
      id: item,
    });
  });
  handleApiResponse(() =>
    ListProjectInfos({ page: 1, size: 1234, status: 1 })
  ).then((res) => {
    if (res.code == 0) {
      checkDetailForm.value.projectList = res.data.list || [];

      setStorageWithEvent("refresh_checkList");
    }
  });
};

// 失焦修改基本信息
const handleBlurEdit = () => {
  ElMessage({
    message: "保存成功",
    type: "success",
  });
};

// 1-1 新增受检人
const insert_customer_drawer = ref(false);
const insertCustomerRef = ref(null);
const customer_loading = ref(false);
const handleClickInsertCustomer = () => {
  insert_customer_drawer.value = true;
};
const handleSuccessInsertCustomer = (data) => {
  // console.log(data);

  customer_loading.value = false;

  handleApiResponse(() =>
    ListProjectInfos({ page: 1, size: 1234, status: 1 })
  ).then((res) => {
    if (res.code == 0) {
      // console.log(res);

      if (data) {
        userStore.updateCheckDetailForm({
          id: null,
          relationId: data.id || null,
          relationName: data.customerName || "", // 受检人姓名
          phone: data.phone || "",
          sex: data.sex || null,
          age: data.age || 0, // 年龄
          birthday: data.birthday || null,
          headUrl: data.headUrl || "",
          address: data.address || "", // 地址
          customerId: data.id || null,
          customerName: data.customerName || "",
          customerTel: data.customerTel || "",
          customerPhone: data.customerTel || "",
          baseRelationId: data.baseRelativeId || 0,
          baseRelativeId: data.baseRelativeId || 0,
          baseRelationName: data.baseRelativeName || "本人",
          baseRelativeName: data.baseRelativeName || "本人",
          workEnvironment: data.workEnvName, // 工作环境
          occupation: data.occupationName, // 职业
          eyeDistance: data.eyeUsageDistanceName, // 用眼距离
          medicalCardNumber: data.medicalCardNumber,
          projectList: res.data.list || [],
        });
        // console.log(checkDetailForm.value);
      }
    }
  });

  insert_customer_drawer.value = false;
};
const handleErrorInsertCustomer = () => {
  customer_loading.value = false;
};
const handleAffirmCustomer = () => {
  insertCustomerRef.value.handleSubmitCustomer();
};

const workEnvList = ref([]); // 工作环境列表
const occupationList = ref([]); // 职业列表
const eyeDistanceList = ref([]); // 用眼距离列表
async function getOccupationList() {
  handleApiResponse(() => ListCustomerOccupation()).then((res) => {
    if (res.code == 0) {
      occupationList.value = res.data.list || [];
    }
  });
}
async function getWorkEnvList() {
  handleApiResponse(() => ListCustomerWorkEnv()).then((res) => {
    if (res.code == 0) {
      workEnvList.value = res.data.list || [];
    }
  });
}
async function getEyeUsageDistanceList() {
  handleApiResponse(() => ListCustomerEyeUsageDistance()).then((res) => {
    if (res.code == 0) {
      eyeDistanceList.value = res.data.list || [];
    }
  });
}

let cleanup;
onMounted(() => {
  cleanup = watchStorage("change_checkDetailForm", (newValue) => {
    // 同步到Pinia状态
    // userStore.updateCheckDetailForm(newValue);
    // 这里可以添加其他需要执行的逻辑
    console.log("监听到数据变化:", newValue);
  });

  // 组件卸载时清理监听
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});

// 监听工作环境/职业/用眼距离是否有值，没有值则获取
watchEffect(() => {
  if (cutStatus.value == 2 && flowActiveIndex.value == 1) {
    if (
      !workEnvList.value ||
      workEnvList.value.length == 0 ||
      !occupationList.value ||
      occupationList.value.length == 0 ||
      !eyeDistanceList.value ||
      eyeDistanceList.value.length == 0
    ) {
      getOccupationList();
      getWorkEnvList();
      getEyeUsageDistanceList();
    }
  }
});
</script>

<style scoped lang="scss">
:deep(.el-descriptions__label) {
  min-width: 6rem !important;
}

:deep(
    .el-descriptions__body
      .el-descriptions__table.is-bordered
      .el-descriptions__cell
  ) {
  padding: 0.2rem !important;
}

.ellipsis-single {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>